﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.ApplicationPages;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Administration;
using System.Data;
using System.Collections.Generic;

namespace zevenseas.ClassicTheme
{
    public partial class ApplyTheme : LayoutsPageBase
    {
public void ApplyThemeBtn_Click(object sender, EventArgs e)
{
    SPWeb currentWeb = SPContext.Current.Web;
            
    //If the theme was already applied to the site, 
    //SharePoint raises an error that the theme was already applied.
    try{currentWeb.ApplyTheme(ThemesDropDown.SelectedValue);}
    catch (SPException exception){}

    SPLongOperation addThemeOperation = new SPLongOperation(this.Page);
    addThemeOperation.Begin();
    addThemeOperation.LeadingHTML = (ApplyAllWebs.Checked) ? 
        "Applying the theme to the current web and it's subsites" : "Applying the theme to the current web";
    string cssUrl = ApplyAlternateCSS(currentWeb.Url);
    if (ApplyAllWebs.Checked)
    {
        foreach (SPWeb subweb in currentWeb.Webs)
        {
            subweb.AlternateCssUrl = cssUrl;
            subweb.Update();
        }
    }
    currentWeb.AlternateCssUrl = cssUrl;
    currentWeb.Update();
    addThemeOperation.End(currentWeb.Url + "/_layouts/settings.aspx");
}

      
        

        protected void Page_Load(object sender, EventArgs e)
        {
            if (ThemesDropDown != null)
            {
                if (ThemesDropDown.SelectedValue != null && !string.IsNullOrEmpty(ThemesDropDown.SelectedValue))
                {
                    SPWebApplication webApplication = SPWebApplication.Lookup(new Uri(SPContext.Current.Site.Url));
                    DataView themesDataView = webApplication.GetAllThemes();
                    themesDataView.RowFilter = "TemplateID like '" + ThemesDropDown.SelectedValue +"'";
                    ThemePicture.ImageUrl = "/_layouts/" + themesDataView.ToTable().Rows[0]["Preview"].ToString();
                }
            }

            if (!Page.IsPostBack)
                BindData();
        }

        private void BindData()
        {
            ThemesDropDown.DataSource = FilterThemes();
            ThemesDropDown.DataTextField = "DisplayName";
            ThemesDropDown.DataValueField = "TemplateID";
            ThemesDropDown.DataBind();
        }

        private List<string> BlockedThemes(ref List<string> blockedThemes)
        {
            SPWebApplication webApplication = SPContext.Current.Site.WebApplication;
            Themes settings = webApplication.GetChild<Themes>("ThemeCollection");
            if (settings != null)
            {
                if (settings.TemplateIDs != null)
                {
                    blockedThemes = settings.TemplateIDs;
                }
            }

            return blockedThemes;
        }

        private DataView FilterThemes()
        {
            DataTable allThemesTable = SPContext.Current.Site.WebApplication.GetAllThemes().ToTable();

            List<string> blockedThemes = new List<string>();
            BlockedThemes(ref blockedThemes);

            DataTable themesTable = new DataTable();
            DataTable blockedThemesTable = new DataTable();

            themesTable = allThemesTable.Clone();
            blockedThemesTable = allThemesTable.Clone();

            foreach (DataRow row in allThemesTable.Rows)
            {
                bool isBlocked = false;
                foreach (string templateId in blockedThemes)
                {
                    if (row["TemplateID"].ToString() == templateId)
                    {
                        isBlocked = true;
                        break;
                    }
                }

                if (!isBlocked)
                {
                    DataRow themeRow = themesTable.NewRow();
                    themeRow.ItemArray = row.ItemArray;
                    themesTable.Rows.Add(themeRow);
                }
            }

            return new DataView(themesTable);
        }

private string ApplyAlternateCSS(string webUrl)
{
    string cssUrl = string.Empty;

    //When Applying a theme, some copy action takes place behind the scenes.
    //To be sure that everything is populated we get a new instance of the site and web
    //And to be extra, extra safe, we are going to a lot of 'Exists' queries on the folders ;)
    using (SPSite site = new SPSite(webUrl))
    {
        using (SPWeb themeWeb = site.OpenWeb())
        {
            SPFolder themesFolder = themeWeb.Folders["_themes"];
            if (!themesFolder.Exists)
            {
                themesFolder = themeWeb.Folders["_themes"];
            }

            SPFolder themeFolder = themesFolder.SubFolders[ThemesDropDown.SelectedValue];
            if (themeFolder.Exists)
            {
                cssUrl = themeFolder.Url + "/theme.css";
            }
        }
    }

    return cssUrl;
}

        
    }
}
